// Background Script - 插件后台逻辑
chrome.runtime.onInstalled.addListener(() => {
    console.log('网页智能总结插件已安装');
    
    // 设置默认侧边栏
    chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
});

// 处理扩展图标点击
chrome.action.onClicked.addListener((tab) => {
    // 打开侧边栏
    chrome.sidePanel.open({ windowId: tab.windowId });
});

// 维护所有 sidepanel 连接的 Port
const sidepanelPorts = [];

chrome.runtime.onConnect.addListener((port) => {
    if (port.name === 'sidepanel') {
        sidepanelPorts.push(port);
        port.onDisconnect.addListener(() => {
            const idx = sidepanelPorts.indexOf(port);
            if (idx !== -1) sidepanelPorts.splice(idx, 1);
        });
    }
});

// 监听来自content script的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'openSidePanel') {
        chrome.sidePanel.open({ windowId: sender.tab.windowId });
        sendResponse({ success: true });
    }
    if (request.action === 'pageUrlChanged') {
        // 广播给所有 sidepanel，带上 tabId
        const tabId = sender.tab && sender.tab.id;
        for (const port of sidepanelPorts) {
            try {
                port.postMessage({ action: 'pageUrlChanged', url: request.url, tabId });
            } catch (e) {}
        }
    }
});

// 处理标签页更新
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.status === 'complete' && tab.url) {
        // 页面加载完成后，可以在这里做一些初始化工作
        console.log('页面加载完成:', tab.url);
    }
}); 